<template>
	<div id="process-main" > <!-- 排布比赛 -->
		<Title>比赛分组</Title>
		<!-- {{cptt.name}} <br> -->
		<span class="text" id="process-name">{{cptt.name}}</span>
		<span class="text">(参赛人数:{{applyUsers.length}},分组:{{grouping.groupingLengh}})</span>
		<br>
		<span class="text" v-if="grouping.bad">
			建议调整参赛人数
		</span>
		<!-- USERS展示 -->
		<div id="process-users" v-if="!isGroup">
			<div v-for="(user,index) in applyUsers" >
				<el-tag
				:title="'id:'+user.uid"
				v-show = "user.isShow"
				:class="{'isSelect':user.isSelect}"
				@click="fill(true,index)"
				>
				  {{user.uname}}
				</el-tag>
			</div>
			<br>
			<el-button @click="makeGroup" type="primary">
				一键排赛
			</el-button>
			<br>
			<!-- grouping.groupingLengh -->
			<!-- <div id="grouplingLenght">
				<input type="text" 
					v-for="(v,index) in grouping.groupingLengh"
					v-model="v"
					@change="changeGLength(v,index)"
				>
			</div> -->
		</div>
		<el-popover
		  v-else
		  placement="top"
		  width="160"
		  v-model="visible">
			<p>确定要清空分组嘛？</p>
			<div style="text-align: right; margin: 0">
				<el-button size="mini" type="text" @click="visible = false">取消</el-button>
				<el-button type="primary" size="mini" @click="visible = false;dropGrouping()">确定</el-button>
			</div>
			<el-button slot="reference">重新分组</el-button>
		</el-popover>
		
		<el-button 
		 @click="postGroup"
		 :loading="isLoad"
		 :disabled="info? true:false"
		>
			{{info? info:'上传分组数据'}}
		</el-button>
		<!-- 一个赛程 -->
		<transition name="tag">
		<div>
			<div
			class="pro-game" 
			@click.captrue="delChoose"
			v-for="(group,index) in grouping.grouping"
			>
				<!-- 其中的参赛者 -->
				<el-tag
				v-for="(i,index2) in group"
				class="pro-user"
				:title="index+'-'+i.id"
				effect="plain"
				@click.stop = "i.length==undefined? choose(index,index2):fill(false,index,index2)"
				:class="{'isSelect':i.isSelect}"
				v-show="i.isShow || i.isShow==undefined"
				>
				<!-- {{i.length==undefined}}//对象的length是undefined -->
					{{i.uname}}
				</el-tag>
				<br>
			</div>
		</div>
		</transition>
	</div>
</template>

<script>
import { Loading } from 'element-ui';
import Vue from 'vue'
export default{
	data(){
		return{
			applyUsers:[
				{id:"id",uid:"uid",name:"uname"}
			],
			// isShow:[],
			cptt:"",
			exchange:null,
			grouping:{},//分组信息
			index:null,
			isGroup:false,
			visible:false,
			isFill:null,
			isLoad:false,//上传分组数据,
			info:"",
			type:0// 0->个人   1->组队
		}
	},
	props:["showMain"],
	created() {
		// console.log(this.showMain)
		//CPTT
		this.index = this.$route.query.index
		if(this.$store.state.cptts.length > 0)
			{
				this.cptt = this.$store.state.cptts[this.index]
				this.type = /^个人/.test(this.cptt.type)? 0:1
			}
		else {
			setTimeout(()=>{
				this.cptt = this.$store.state.cptts[this.index]
				this.type = /^个人/.test(this.cptt.type)? 0:1
			},1000)
		}
		//USERS
		// 对其进行修改之后
		// 需要重新放回sessionStorage
		// 不然刷新出问题
		let data = window.sessionStorage.getItem('applyUsers')//typeof => String
		if(data)
		{
			this.applyUsers = JSON.parse(data)
			setTimeout(()=>{
				window.sessionStorage.clear()
			},1000*60*  60*24)//十分钟后清除

			this.applyUsers.forEach(item => {
			    item.isShow = true;
				item.isSelect = false;
			})
		}
		else
			this.applyUsers = "获取报名人员异常,请重新获取"
		//赛事排布
		//$route.query.isGrouping :非实时获取,刷新会报错
		//用 document.location.hash 修改
		this.isGroup = this.$route.query.isGrouping == "true"
			this.isGroup? this.showGrouping() : this.makeGrouplength();

	},
	methods:{
		changeApplyUsers(index,key,newValue){
			//下标,属性,新值
			// Vue 不能检测对象属性的添加或删除
			// 需要使用Vue.set(Obj,index,newData)
			// this.applyUsers[index].isSelect = true //=>不可行
			let newData = this.applyUsers[index]
			newData[key] = newValue
			Vue.set(this.applyUsers,index,newData)
		},
		changeGrouping(index1,index2,key,newValue){
			let newData = this.grouping.grouping[index1][index2]
			newData[key] = newValue
			Vue.set(this.grouping.grouping[index1],index2,newData)
			// console.log(index1+","+index2+":"+key+"=>"+newData[key])
		},
		change(start,end){
			console.log("交换=>",start,"&&",end)
			//消失+取消选中
			this.changeGrouping(...start,"isShow",false)
			this.changeGrouping(...end,"isShow",false)
			this.changeGrouping(...start,"isSelect",false)
			//需要置换的用户
			let user1 = this.grouping.grouping[start[0]][start[1]];
			let user2 = this.grouping.grouping[end[0]][end[1]];
			const PostData = [//交换好的
				{ id:user1.id, grouping:user2.grouping },
				{ id:user2.id, grouping:user1.grouping }
			]
			console.log(PostData)
			//后端交换
			let load = Loading.service({ fullscreen: true })
			let zzc = document.getElementsByClassName('el-loading-mask')[0]
			zzc.setAttribute("style","top:"+(60+(this.showMain? 50:0))+"px;left:20%")
			axios.post('./api/MakeGroup',PostData)
				.then(info=>{
					load.close()
					this.$message({
						message:info.data.info ,
						type: info.data.type,
						duration:info.data.type=="warning"? 0:3000,
						showClose:true
					});
					//需要刷新一下USER
					/*
					未做
					*/
				   
					//交换
					if(info.data.type==="success")//成功
						setTimeout(()=>{
							Vue.set(this.grouping.grouping[start[0]],start[1],user2)
							Vue.set(this.grouping.grouping[end[0]],end[1],user1)
						},600)
					//展示
					setTimeout(()=>{
						this.changeGrouping(...start,"isShow",true)
						this.changeGrouping(...end,"isShow",true)
					},1000)
				}).catch(error=>{
					load.close()
					console.log(error)
					this.$message({ message: '服务器异常',type: 'warning'});
					this.changeGrouping(...start,"isShow",true)
					this.changeGrouping(...end,"isShow",true)
				})
		},
		//交换之前的选择
		choose(index1,index2){
			// console.log(index1,index2)
			// console.log(this.grouping.grouping[index1][index2].uname)
			if(this.exchange === null)//选择第一个
			{
				this.exchange = [index1,index2]
				this.changeGrouping(index1,index2,"isSelect",true)
			}
			else if(index1==this.exchange[0])//同一分组不交换
				{//选择新的
					this.changeGrouping(...this.exchange,"isSelect",false)
					this.exchange = [index1,index2]
					this.changeGrouping(index1,index2,"isSelect",true)
				}
				else//交换
				{
					this.change(this.exchange,[index1,index2])
					this.exchange = null
				}
		},
		delChoose(){
			// console.log("调用")
			if(this.exchange != null)
			{
				this.changeGrouping(...this.exchange,"isSelect",false)
				this.exchange = null
			}
		},
		//没有分组，建议分组
		adviceGrouping(){
			let num = this.usernum//总人数
			// var num = 14
			//测试
			if(!(this.type === 0
			|| parseInt(num/8) === num/8 // 4*2
			|| parseInt(num/12) === num/12)) // 6*2
				{
					console.log("报名人数不太合理哦!")
					// 请协调比赛人数
					return null;
				}
			for(var i=6;i>0;i--)//i人一组
			{
				if(num%i === 0)
				{
					var groupingLengh = new Array(num/i).fill(i)
					break//刚好六人一组
				}
				if(num%i < num/i && i<6)
				{
					let zu = parseInt(num/i)
					let remaining = num%i
					var groupingLengh = new Array(zu).fill(i)
					while(remaining>=0)
					{
						groupingLengh[remaining-1] += 1
						remaining -= 1
					}
					break;
				}
			}
			let grouping = []
			groupingLengh.forEach(e=>{
				let g = []
				let length = e
				while(length-- >0)
					g.push([])
				grouping.push(g)
			})
			return {
					grouping,
					groupingLengh,
					bad: i>=5? false:true
				   }
			 
		},
		//没有分组，创建分组
		makeGrouplength(){
			// console.log(/^组队/.test(this.cptt.type))
			// console.log(this.adviceGrouping())
			var fenzu =()=>{
				this.$confirm('建议分组:'+adviceGrouping.groupingLengh,'建议分组',{
								confirmButtonText: '采用(就这个了)',
								cancelButtonText: '不采用(我自己来)',
								closeOnClickModal:false,
								showClose:false
				}).then(()=>{
					this.grouping = adviceGrouping
				}).catch(()=>{//不采用
						this.$prompt('请输入分组(","间隔//总人数:'+this.usernum+')', '提示', {
								confirmButtonText: '确定',
								cancelButtonText: '使用建议分组',
								inputPattern: /^([2-6],)*[2-6]$/,
								inputErrorMessage: '分组有误(格式有误,或人数不符)',
								closeOnClickModal:false,
								showClose:false,
								inputValidator:value=>{
									let result = value.match(/\d/g)
									let sum = 0
									for (let i of result)
										sum += Number(i)
									return sum == this.usernum
								}
						}).then((value)=>{
							console.log(value)
							adviceGrouping = {
								grouping:value.value.match(/\d/g).map(i=>Number(i)),
								bad:false
							}
							this.grouping = adviceGrouping
						}).catch(()=>{
							this.grouping = adviceGrouping
						})
				})
			}
			let adviceGrouping = this.adviceGrouping()
			// console.log(adviceGrouping)
			if(adviceGrouping === null)
				{
					this.$alert('这是一个组队比赛,每组人数必须是4人或者6人,现在的人数无法分组,请协调报名人员', '报名人数不合理', {
						confirmButtonText: '确定',
						callback: action => {
							this.$router.push('/admin/setC?open='
									+this.$route.query.index)
						},
						showClose: false
					})
					return;
				}
			if(adviceGrouping.bad)
			{
				this.$confirm('建议分组:'+adviceGrouping.groupingLengh
					+',是否调整参赛人员?','参赛人数不合适',{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type:'warning',
					closeOnClickModal:false,
					showClose:false
				}).then(() => {
					console.log("yes")
					this.$router.push('/admin/setC?open='
						+this.$route.query.index)//打开对应的参赛人员栏
				}).catch(() => {
					fenzu()
				})
			}
			else{
				fenzu()
			}
			
		},
		//根据分组，加入user
		makeGroup(){
			this.info = false
			if (this.isGroup == true)
				return null
			const groupingLengh = this.grouping.groupingLengh
			let grouping = []
			groupingLengh.forEach(e=>{
				grouping.push([])
			})
			//不能直接赋值！
			let users = [...this.applyUsers]// ...
			// let ls_users = [] //grouping.flat()
			//users => 用来pop进group
			//ls_users => 修改grouping属性
			for (let index in groupingLengh)
				for(let i=0;i<groupingLengh[index];i++)
					{
						let randint = Math.floor(Math.random()*users.length)
						let user = users.splice(randint,1)[0];
						user.grouping = index
						// ls_users.push(user)
						grouping[index].push(user)
					}
			let load = Loading.service({ fullscreen: true })
			let zzc = document.getElementsByClassName('el-loading-mask')[0]
				//考虑是否显示头部
			zzc.setAttribute("style","top:"+(60+(this.showMain? 50:0))+"px;left:20%")
			axios.post('./api/MakeGroup',grouping.flat().map(e=>//过滤一下
											{
												return{
													id:e.id,
													grouping:e.grouping
												}
											})
				 )
				 .then(info=>{
					 load.close()
				 	// setTimeout(()=>{
				 		this.$message({
				 			message:info.data.info ,
				 			type: info.data.type,
				 			duration:info.data.type=="warning"? 0:3000,
				 			showClose:true
				 		});
				 	// },500)
					//修改Grouping
					this.grouping = {
						grouping,
						groupingLengh,
						bad:false
					}
					//修改hash
					this.isGroup = true
					this.changeHash("isGrouping",this.isGroup)
					//刷新USER
					window.sessionStorage.setItem(
						'applyUsers',
						JSON.stringify(grouping.flat())
					)
				 }).catch(error=>{
					load.close()
				 	console.log(error)
				 	this.$message({ message: '服务器异常',type: 'warning'});
					// this.dropGrouping()//测试-删除分了一半儿的?
				 })

		},
		//分组已有,展示分组
		showGrouping(){
			let groupKey = []
			let group = []
			// group.push([],[],[],[],[],[])
			// console.log(this.applyUsers)
			this.applyUsers.forEach(e=>{
				// console.log(e)
				let key = Number(e.grouping)
				if(!groupKey.includes(key))
				{
					groupKey.push(key)
					group[key]=[]
				}
				group[key].push(e)
			})
			group = group.filter(e=>e!=undefined)//去除空元素
			let groupingLengh = []//每个分组的长度
			group.forEach(e=>{
				groupingLengh.push(e.length)
			})
			// console.log(group)
			this.grouping = {
				grouping:group,
				groupingLengh,
				bad:false
			}
			//测试
			// this.$nextTick(()=>{//更新好之后
			// // console.log(this.$refs.imgtest)
			// 	this.refToImg(this.$refs.imgtest)
			// })
			
		},
		//删除分组
		dropGrouping(){
			let load = Loading.service({ fullscreen: true })
			let zzc = document.getElementsByClassName('el-loading-mask')[0]
				//考虑是否显示头部
			zzc.setAttribute("style","top:"+(60+(this.showMain? 50:0))+"px;left:20%")
			
			let dG = () =>{
				let G = []
				this.grouping.grouping.forEach(e=>{
					let g = []
					let length = e.length
					while(length-- >0)
						g.push([])
					
					G.push(g)
				})
				this.grouping.grouping = G
				this.isGroup = false
				this.changeHash("isGrouping",this.isGroup)
				
				// //拿回User
				// console.log(this.applyUsers)
				// this.applyUsers.forEach(e=>{
				// 	e.grouping="null"
				// })
			}
			// console.log(this.cptt)
			axios.post('./api/DropGroup',{
				id:this.cptt.id
			}).then(info=>{
				load.close()
				this.$message({
					message:info.data.info ,
					type: info.data.type,
					duration:info.data.type=="warning"? 0:3000,
					showClose:true,
				});
				dG();
			}).catch(error=>{
				console.log(error)
				load.close()
				this.$message({ message: '服务器异常',type: 'warning'});
			})
		},
		fill(tag,...index){
			//tag==true:选择用户  tag==false:选择位置
			if(tag)//选择用户
				if(this.isFill==null)//第一个
				{
					this.changeApplyUsers(...index,"isSelect",true)
					this.isFill = index[0]
				}else{
					this.changeApplyUsers(this.isFill,"isSelect",false)
					this.changeApplyUsers(...index,"isSelect",true)
					this.isFill = index[0]
				}
			else
				if(this.isFill==null)//没选上边的
					return;
				else{//放进去
					let user = this.applyUsers.splice(this.isFill,1)[0]
					user.isShow=true
					user.isSelect=false
					axios.post('./api/MakeGroup',[{id:user.id,grouping:user.grouping}])
						 .then(info=>{
							 console.log(info)
							 this.$message({
							 	message:info.data.info ,
							 	type: info.data.type,
							 	duration:info.data.type=="warning"? 0:3000,
							 	showClose:true
							 });		   
							 //交换
							 if(info.data.type==="success"){
								 Vue.set(this.grouping.grouping[index[0]],index[1],user)
								 this.isFill=null
							 }else{
								 throw new Error("ERROR");
							 }
						 })
						 .catch(e=>{
							 console.log(e)
							 this.$message({ message: '服务器异常',type: 'warning'});
							 this.applyUsers.push(user)
						 })
				}
		},
		//修改分组
		changeGLength(value,index){
			console.log(value,index)
		},
		//上传分组数据
		postGroup(){
			this.isLoad = true
			let data = this.grouping.grouping
			let result = null
			result = {
				id:this.cptt.id,
				info:data.map(group=>{
						return group.map(e=>{
								return {
										name:e.uname,
								}
							})
						})
			}
			if(result)
			// console.log(result)
			axios.post('./api/SaveGroup',result)
				 .then(e=>{
					 console.log(e);
					 setTimeout(()=>{
						 this.isLoad = false;
						 this.info = '上传成功'
						 console.log(this.isLoad);
					 },500)
					 })
				 .catch(e=>{
					 console.log(e)
					 setTimeout(()=>{
						 this.isLoad = false;
					 },500)
					 })
		},
	},
	computed:{
		usernum(){
			return this.applyUsers.length
		}
	}
}
</script>

<style lang="scss">
#process-main{
	#process-name{
		font-size: 1.45rem;
		font-weight: 700;
	}
	.pro-game{
		margin-top: 20px;
		padding-left: 20px;
		border: 1px solid wheat;
		width:200px;
		.pro-user{
			display: block;
			width: 100px;
			margin-top: 10px;
		}
	}
	#process-users{
		display: flex;
		flex-flow: row wrap;
		.el-tag{
			margin: 2px;
		}
		#grouplingLenght{
			width: 100%;
			display: flex;
			input{
				flex:1;
				overflow: hidden;
				margin-right: 10px;
			}
		}
	}
	.isSelect{
		border: #13CE66 1px solid;
	}
	
	// .tag-enter-active {
	//   transition: all .5s cubic-bezier(0.56, 0.27, 0.46, 1.15);
	// }
	// .tag-leave-active {
	//   transition: all .5s cubic-bezier(0.56, 0.27, 0.46, 1.15);
	// }
	// .tag-enter{
	// 	transform: translateY(30px);
	// 	opacity: 0;
	// }
	// .tag-leave-to
	// {
	//   transform: translateY(-30px);
	//   opacity: 0;
	// }
}
// .el-loading-mask{
// 	top:110px;
// 	left:20%;
// }
</style>
